package org.slg.oracleproject.config;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slg.oracleproject.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 1. 从请求头获取Authorization头
        String authHeader = request.getHeader("Authorization");
        String token = null;
        // 2. 提取Token：支持两种格式（带Bearer前缀/纯Token）
        if (authHeader != null && !authHeader.isEmpty()) {
            if (authHeader.startsWith("Bearer ")) {
                // 格式1：Bearer <token> → 提取<token>
                token = authHeader.substring(7).trim();
                logger.debug("检测到带Bearer前缀的Token，已提取纯Token");
            } else {
                // 格式2：纯Token（无前缀）→ 直接使用
                token = authHeader.trim();
                logger.debug("检测到无前缀的Token，直接使用");
            }
        }
        // 3. 验证Token并设置认证信息
        if (token != null) {
            try {
                // 验证Token有效性
                if (jwtTokenUtil.validateToken(token)) {
                    // 解析角色和用户名
                    List<String> roles = jwtTokenUtil.getRolesFromToken(token);
                    List<GrantedAuthority> authorities = roles.stream()
                            .map(SimpleGrantedAuthority::new)
                            .collect(Collectors.toList());
                    String username = jwtTokenUtil.getUsernameFromToken(token);

                    // 创建认证对象并设置到上下文
                    Authentication auth = new UsernamePasswordAuthenticationToken(
                            username,
                            null,
                            authorities
                    );
                    SecurityContextHolder.getContext().setAuthentication(auth);
                    logger.debug("Token验证通过，用户[{}]已认证", username);
                } else {
                    logger.warn("Token无效或已过期");
                }
            } catch (Exception e) {
                logger.error("Token解析失败：{}", e.getMessage());
            }
        } else {
            logger.debug("未从Authorization头中获取到Token");
        }
        // 4. 继续执行过滤器链
        filterChain.doFilter(request, response);
    }
}